<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>权限管理</el-breadcrumb-item>
			<el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>

		<el-card>
			<!-- 添加角色按钮 -->
			<el-row>
				<el-col :span="24">
					<el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
				</el-col>
			</el-row>

			<!-- 角色列表 -->
			<el-table :data="rolesList" border stripe>
				<!-- 展开列 -->
				<el-table-column type="expand">
					<template slot-scope="scope">
						<el-row type="flex" align-items="center" :class="['bdbottom', i1==0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
							<el-col :span="5">
								<el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
								<i class="el-icon-caret-right"></i>
							</el-col>
							<el-col :span="19">
								<el-row type="flex" align-items="center" :class="[i2==0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children"
								 :key="item2.id">
									<el-col :span="6">
										<el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
										<i class="el-icon-caret-right"></i>
									</el-col>
									<el-col :span="18">
										<el-tag v-for="(item3, i3) in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
						<!-- <pre>
								{{scope.row.children}}
						</pre> -->
					</template>
				</el-table-column>
				<!-- 索引列 -->
				<el-table-column type="index" label="#"></el-table-column>
				<el-table-column prop="roleName" label="角色名称"></el-table-column>
				<el-table-column prop="roleDesc" label="角色描述"></el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
						<el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 角色编辑对话框 -->
			<el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%">
				<el-form :modle="editForm">
					<el-form-item label="角色名称">
						<el-input v-model="editForm.editForm"></el-input>
					</el-form-item>
					<el-form-item label="角色描述">
						<el-input v-model="editForm.roleDesc"></el-input>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="editDialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="editRole(editForm.roleId)">确 定</el-button>
				</span>
			</el-dialog>
			<!-- 角色添加对话框 -->
			<el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
				<el-form :model="addForm" :rules="addRolesRules" ref="addRolesRef" label-width="100px">
					<el-form-item label="角色名称"  prop="roleName">
						<el-input v-model="addForm.roleName"></el-input>
					</el-form-item>
					<el-form-item label="角色描述" prop="roleDesc">
						<el-input v-model="addForm.roleDesc"></el-input>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="addDialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="addRoles">确 定</el-button>
				</span>
			</el-dialog>
			<!-- 分配权限对话框 -->
			<el-dialog
			  title="分配权限"
			  :visible.sync="setRightDialog"
			  width="50%">
				<!-- 
					属性说明:
					default-expand-all 默认展开节点
					node-key 唯一标识
					default-checked-keys 默认展开的节点的 key 的数组
					ref 引用
				-->
			 <el-tree :data="rightsLits" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
			  <span slot="footer" class="dialog-footer">
			    <el-button @click="setRightDialog = false">取 消</el-button>
			    <el-button type="primary" @click="allotRights">确 定</el-button>
			  </span>
			</el-dialog>
		</el-card>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				rolesList: [],
				editDialogVisible: false,
				editForm: {},
				// 显示或隐藏添加角色对话框
				addDialogVisible: false,
				// 存储添加角色表单信息
				addForm: {
					"roleName": '',
					"roleDesc": ''
				},
				// 添加角色验证规则
				addRolesRules: {
					roleName: [{
							required: true,
							message: '请输入角色名称',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 5,
							message: '长度在 3 到 5 个字符',
							trigger: 'blur'
						}
					],
					roleDesc: [{
							required: true,
							message: '请输入角色描述',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 5,
							message: '长度在 3 到 5 个字符',
							trigger: 'blur'
						}
					],
				},
				// 控制分配权限对话框的显示和隐藏
				setRightDialog : false,
				// 存放获取到的权限列表
				rightsLits: [],
				// 树形控件数据绑定对象
				treeProps: {
					children: 'children',
					label: 'authName'
				},
				// 默认勾选的节点id值数值
				defKeys: [],
				// 保存即将要分配权限的角色id
				activeRoleId: null
			}
		},
		// 生命周期函数
		created() {
			this.getRolesList()
		},
		methods: {
			// 获取角色列表
			async getRolesList() {
				// 发起axios请求
				const data = await this.$http.get('roles')

				if (data.data.meta.status !== 200) {
					return this.$message.error('获取角色列表失败！')
				}
				this.rolesList = data.data.data
			},
			// 点击编辑按钮打开对话框
			async showEditDialog(id) {
				// 发起请求
				const data = await this.$http.get('roles/' + id)
				if (data.data.meta.status !== 200) {
					return this.$message.error('获取角色失败！')
				}
				this.editDialogVisible = true
				this.editForm = data.data.data
			},
			// 修改角色
			async editRole(id) {
				// 发起请求
				const data = await this.$http.put('roles/' + id, this.editForm)
				if (data.data.meta.status !== 200) {
					return this.$message.error('修改角色失败！')
				}
				this.$message.success('修改角色成功！')
				this.getRolesList()
				this.editDialogVisible = false
			},
			// 删除角色
			async deleteRole(id) {
				const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch((error) => { //捕获用户取消行为
					return error
				})

				// 如果用户点击了确定返回字符串 confirm
				// 如果用户点击了取消返回字符串 cancel
				if (confirmResult !== 'confirm') {
					return this.$message.info('已取消删除')
				}
				// 发起请求
				const data = await this.$http.delete('roles/' + id)
				if (data.data.meta.status !== 200) {
					return this.$message.error('删除角色失败！')
				}
				this.$message.success('删除角色成功！')
				this.getRolesList()
			},
			// 添加角色
			addRoles() {
				this.$refs.addRolesRef.validate(async (valid) => {
					// 判断预验证是否通过
					if(!valid) {
						return this.$message.error('表单验证失败')
					}
					// 发起请求
					const data = await this.$http.post('roles', this.addForm)
					// 判断状态码
					if(data.data.meta.status !== 201	) {
						return this.$message.error('添加角色失败')
					}
					this.$message.success('添加角色成功')
					this.addDialogVisible = false
					this.getRolesList()
				})
			},
			// 根据id删除对应的权限
			async	removeRightById(role, rightId) {
				// 弹框提示用户是否删除权限
				
				const confirmResult	= await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
				
				// 判断用户是否删除权限
				if(confirmResult !== 'confirm'){
					return this.$message.info('取消了删除')
				}
				
				const data	=	await	this.$http.delete(`roles/${role.id}/rights/${rightId}`)
				if(data.data.meta.status !== 200) return this.$message.error('删除权限失败')
				// 查询渲染界面会使菜单关闭!不推荐这样使用
				// this.getRolesList()
				
				role.children = data.data.data
				
			},
			// 显示分配权限对话框
			async showSetRightDialog(role) {
				this.activeRoleId = role.id
				// 发起请求获取全部权限对话框
				const data = await this.$http.get('rights/tree')
				// 判断状态码
				if(data.data.meta.status !== 200) {
					return this.$message.error('获取权限数据失败！')
				}
				// 获取到的权限数据保存到 data 中
				this.rightsLits = data.data.data
				// 获取之前先清空数组
				this.defKeys.splice(0, this.defKeys.length);
				// 递归获取三级节点的id
				this.getLeafKeys(role, this.defKeys)
				this.setRightDialog = true
			},
			// 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
			getLeafKeys(node, arr) {
				// 如果当前 node 节点中没有children属性说明是三级节点
				if(!node.children){
					return arr.push(node.id)
				}
				// 只要节点中包含 children 属性则遍历节点
				node.children.forEach((item) => {
					// 重新调用函数把新的节点传进去
					this.getLeafKeys(item, arr)
				})
			},
			// 分配权限函数
			async allotRights() {
				const keys = [
					// ... 展开运算符 把数组中的每个值都散出来
					...this.$refs.treeRef.getCheckedKeys(),
					...this.$refs.treeRef.getHalfCheckedKeys()
				]
				// 把数组转换成字符串以 , 拼接
				const idStr = keys.join(',')
				
				const data = await this.$http.post(`roles/${this.activeRoleId}/rights`, {rids : idStr})
				
				if(data.data.meta.status !== 200) {
					return this.$message.error('分配权限失败！')
				}
				
				this.$message.success('分配权限成功！')
				this.getRolesList()
				this.setRightDialog = false
			},
		}
	}
</script>

<style lang="less" scoped>
	.el-tag {
		margin: 8px 8px 8px 0;
	}

	.bdtop {
		border-top: 1px solid #efefef;
	}

	.bdbottom {
		border-bottom: 1px solid #efefef;
	}
	
	.vcenter {
		display: flex;
		align-items: center;
	}
</style>
